package com.cbtx.module_sp.ui.activity

import android.app.Activity
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.cbtx.module.base.ui.BaseActivity
import com.cbtx.module.base.ui.BaseFragmentPagerAdapter
import com.cbtx.module.base.ui.BaseVMActivity
import com.cbtx.module.common.bean.BannerBean
import com.cbtx.module_sp.R
import com.cbtx.module_sp.ui.vm.AdvActivityVM
import com.txcb.lib.base.utils.LogUtil
import com.txcb.lib.base.utils.UIUtil
import kotlinx.android.synthetic.main.sp_fragment_adv_video.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.Serializable

//广告页面
class AdvActivity: BaseVMActivity<AdvActivityVM>(), SurfaceHolder.Callback,
    MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnPreparedListener,
    MediaPlayer.OnCompletionListener {

      var mMediaPlayer: MediaPlayer? = null

    var position =0
    companion object{
        fun start(activity: Activity?,bannerItemList:ArrayList<BannerBean.BannerItem>){
            val intent = Intent(activity,AdvActivity::class.java)
            intent.putExtra("bannerItemList",bannerItemList)
            activity?.startActivity(intent)
        }
    }

    override fun getPresenterClazz(): Class<AdvActivityVM> {
        return AdvActivityVM::class.java
    }

    override fun getLayoutId(): Int {

        return R.layout.sp_fragment_adv_video
    }

    override fun initView(savedInstanceState: Bundle?) {

        mVM.getIntent(intent)


        mVM.bannerItemList.observe(this, Observer {
            initPlayVideo()
        })
    }

    override fun onMyViewClick(view: View) {

    }

    override fun getData() {

    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        finish()
        return super.onTouchEvent(event)
    }






    /**
     * 播放视频
     */
    fun initPlayVideo() {
        if (mMediaPlayer == null) {
            //实例化MediaPlayer对象
            mMediaPlayer = MediaPlayer()

            val mHardwareDecoder = false
            // 不维持自身缓冲区，直接显示
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && mHardwareDecoder) {
                mSurfaceView!!.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
            }
            mSurfaceView.getHolder().setFixedSize(UIUtil.getWidowsWidth(mActivity), UIUtil.getWidowsHeight(mActivity));
            mSurfaceView!!.holder.setKeepScreenOn(true) //保持屏幕常亮
            mSurfaceView!!.holder.addCallback(this)
        }
    }


    override fun onDestroy() {
        //释放内存，MediaPlayer底层是运行C++的函数方法，不使用后必需释放内存
        if (mMediaPlayer != null) {
            if (mMediaPlayer!!.isPlaying) {
                mMediaPlayer!!.pause()
                mMediaPlayer!!.currentPosition
            }
            mMediaPlayer!!.release()
            mMediaPlayer = null
        }
        super.onDestroy()
    }


    /**
     * begin
     * 向player中设置dispay，也就是SurfaceHolder。但此时有可能SurfaceView还没有创建成功，所以需要监听SurfaceView的创建事件
     */
    override fun surfaceChanged(p0: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {
        mMediaPlayer?.stop()
    }

    override fun surfaceCreated(p0: SurfaceHolder) {


            play()

    }





    /**
     * end
     * 向player中设置dispay，也就是SurfaceHolder。但此时有可能SurfaceView还没有创建成功，所以需要监听SurfaceView的创建事件
     */


    private fun play() {

        if (position>= mVM.bannerItemList.value!!.size){
            position = 0
        }

        val bannerItem: BannerBean.BannerItem = mVM?.bannerItemList?.value!![position]
        if (bannerItem.bannerType != 2){
            return
        }

        try {
            if (mMediaPlayer == null){
                mMediaPlayer = MediaPlayer()
            }
            //添加播放视频的路径与配置MediaPlayer
            mMediaPlayer?.reset()
            //给mMediaPlayer添加预览的SurfaceHolder，将播放器和SurfaceView关联起来
            mMediaPlayer?.setDisplay(mSurfaceView.holder)
            mMediaPlayer?.setDataSource(bannerItem.bannerImgurl)
            // 缓冲
            mMediaPlayer?.prepare()
            mMediaPlayer?.setOnBufferingUpdateListener(this)
            mMediaPlayer?.setOnPreparedListener(this)
            mMediaPlayer?.setOnCompletionListener(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 缓冲变化时回调
     */
    override fun onBufferingUpdate(p0: MediaPlayer?, p1: Int) {

    }

    /**
     * 准备完成回调
     * 只有当播放器准备好了之后才能够播放，所以播放的出发只能在触发了prepare之后
     */
    override fun onPrepared(p0: MediaPlayer?) {
        mMediaPlayer?.start()

        mIvAdvCover.visibility = View.GONE
//                mMediaPlayer.seekTo(position)

    }

    /**
     * 播放结束时回调
     */
    override fun onCompletion(p0: MediaPlayer?) {
//        mMediaPlayer.start()


        position ++
        play()

        EventBus.getDefault().post("nextAdv")
    }


    fun stopPlay(){
        if (mMediaPlayer != null){
            if (mMediaPlayer?.isPlaying!!){
                mMediaPlayer?.stop()
                mMediaPlayer?.release()

                mMediaPlayer = null
            }
        }
    }




}